package com.company.project.search.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.MD5Util;
import com.company.project.search.cache.MemoryCache;
import com.company.project.search.engine.*;
import com.company.project.search.entity.HotSearch;
import com.company.project.search.entity.Search;
import com.company.project.search.service.HotSearchService;
import com.company.project.search.service.SearchEsService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private HotSearchService hotSearchService;
    @Autowired
    private SearchEsService searchEsService;

    @RequestMapping("/category")
    @ResponseBody
    public DataResult category() {
        JSONArray jArray = new JSONArray();
        jArray.addAll(E1.getInstance().provideCategory());
        jArray.addAll(E2.getInstance().provideCategory());
        jArray.addAll(E3.getInstance().provideCategory());
        jArray.addAll(E4.getInstance().provideCategory());
        jArray.addAll(E5.getInstance().provideCategory());
        jArray.addAll(E6.getInstance().provideCategory());

        JSONArray engine = new JSONArray();
        engine.add(new EngineTag(Engine.ID_E1, "知网"));
        engine.add(new EngineTag(Engine.ID_E2, "北大法宝"));
        engine.add(new EngineTag(Engine.ID_E3, "ArtLib"));
        engine.add(new EngineTag(Engine.ID_E4, "易阅通"));
        engine.add(new EngineTag(Engine.ID_E5, "中国共产党思想理论资源数据库"));
        engine.add(new EngineTag(Engine.ID_E6, "中国经济网"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("category", jArray);
        jsonObject.put("engine", engine);
        DataResult dataResult = new DataResult();
        dataResult.setData(jsonObject);
        return dataResult;
    }

    /*
     *实时接口
     */
    @RequestMapping("/searchInfo")
    @ResponseBody
    public DataResult searchInfo(String token, Integer page, String category) {
        Param p = new Param(token)
                .setCategory(category)
                .setCurPage(page);

        Result data = MemoryCache.getMemoryData(p);
        DataResult dataResult = new DataResult();
        dataResult.setData(data);
        return dataResult;
    }

    @RequestMapping("/preSearch")
    @ResponseBody
    public DataResult preSearchInfo(String token, String page, String category) {

        try {
            Param p = new Param(token).setCategory(category);
            Set<Integer> hashSet = new HashSet<>();
            if (page != null && !"".equals(page)) {
                String[] array = page.split("[p|P]");
                if (array.length > 0) {
                    for (String s : array) {
                        if (s == null || s.isEmpty()) continue;
                        s = s.replaceAll("D", "");
                        int i = Integer.parseInt(s);
                        hashSet.add(i);
                    }
                }
            }
            if (hashSet.isEmpty()) hashSet.add(1);
            for (Integer _page : hashSet) {
                Param param = (Param) p.clone();
                param.curPage = _page;
                if (!MemoryCache.preSearchTaskFound(param)) {
                    Inlets.getInstance().search(param,
                            E1.getInstance(),
                            E2.getInstance(),
                            E3.getInstance(),
                            E4.getInstance(),
                            E5.getInstance(),
                            E6.getInstance()
                    );
                }
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        } catch (NumberFormatException ignored) {

        }
        return new DataResult();
    }

    /**
     * 热搜保存接口
     *
     * @return
     */
    @RequestMapping("/rsSave")
    @ResponseBody
    public DataResult rsSave(String params) {
        String id = MD5Util.MD5(params);

        HotSearch byId = hotSearchService.getById(id);
        if (byId != null) {
            byId.setCount(byId.getCount() + 1);
            hotSearchService.updateById(byId);
        } else {
            HotSearch hotSearch = new HotSearch();
            hotSearch.setId(id);
            hotSearch.setName(params);
            hotSearch.setCount(1);
            hotSearchService.save(hotSearch);
        }

        return DataResult.success();
    }

    /**
     * 热搜接口
     *
     * @return
     */
    @RequestMapping("/rs")
    @ResponseBody
    public DataResult rs() {
        Page page = new Page(1, 10);
        LambdaQueryWrapper<HotSearch> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(HotSearch::getCount);
        Page hotPage = hotSearchService.page(page, queryWrapper);
        return DataResult.success(page);
    }

    /**
     * 本地查询 分页
     *
     * @return
     */
    @RequestMapping("/esQuery")
    @ResponseBody
    public DataResult esQuery(int page, String parms) {
        // 构建查询条件
        // 第一个参数是页数page，第二个参数是每页数据数量pageSize 从0开始
        Pageable pageable = PageRequest.of(page - 1, 50);
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("name", "*" + parms + "*"));
        queryBuilder.withPageable(pageable);
        //QueryBuilders.fuzzyQuery("content", "web")
        // 搜索，获取结果
        org.springframework.data.domain.Page<Search> items = this.searchEsService.search(queryBuilder.build());
        // 总条数
        long total = items.getTotalElements();
        System.out.println("total = " + total);
        List<Search> list = items.getContent();
        Result data = new Result();
        data.list = list;

        return DataResult.success(data);
    }

}
